package com;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public abstract class PublicThread implements Runnable {
	protected ServerSocket serverSocket = null;
	protected Socket socket = null;
	protected Thread thread = null;
	protected boolean isRun = true;
	protected ThreadPool threadPool = null;

	public boolean isRun() {
		return isRun;
	}

	public void newThreadStrat() {
		thread = new Thread(this);
		thread.start();
	}

	protected void closeThread() throws Exception {
		isRun = false;
		boolean ret = false;

		try {
			if (serverSocket != null)
				serverSocket.close();
		} catch (IOException e) {
			ret = true;
		}
		serverSocket = null;

		try {
			if (socket != null)
				socket.close();
		} catch (IOException e) {
			ret = true;
		}
		socket = null;

		if (ret) {
			throw new Exception("");
		}
	}

	protected void addToThreadPool() {
		if (threadPool != null) {
			threadPool.addThread(this.toString(), this);
		}

	}

	protected void removeFromThreadPool() {
		if (threadPool != null) {
			threadPool.removeThread(this.toString());
		}
	}

	protected void sleep(long time){
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			System.out.print(e.getMessage());
		}
	}
	abstract public void close();
}
